package com.solidumgame.martillo.tablewood
{
	import Box2D.Collision.Shapes.b2Shape;
	
	import com.greensock.TweenMax;
	import com.pblabs.engine.PBE;
	import com.pblabs.engine.components.AnimatedComponent;
	import com.solidumgame.martillo.tablewood.events.TableWoodGenericEvent;
	
	import flash.geom.Point;
	
	public class TableWoodLogicComponent extends AnimatedComponent
	{
		protected var spatialComp:TableWoodSpatialComponent;
		protected var position:Point;
		
		public function TableWoodLogicComponent()
		{
			super();
			position = new Point(-500,-500);
		}
		
		override protected function onAdd():void{
			super.onAdd();
			this.registerForUpdates = false;
		}
		
		override protected function onReset():void{
			super.onReset();
			this.registerForUpdates = false;
			spatialComp = TableWoodSpatialComponent(owner.lookupComponentByName("Spatial"));
		}

		override protected function onRemove():void{
			super.onRemove();
			spatialComp = null;
		}
		
		public function throwInTableWood():void{
			
			//owner.setProperty(PropertyReference("@Spatial.position"),new Point(-220, 0));
			this.registerForUpdates = false;
			
			spatialComp.canRotate = false;
			spatialComp.canMove = false;
			
			if(owner)
				owner.eventDispatcher.dispatchEvent(new TableWoodGenericEvent(TableWoodGenericEvent.TABLEWOOD_TRHOW_ENTER));
			
			TweenMax.fromTo(position,2,{x:-spatialComp.size.x-200,y:350},{bezier:[{x:-20,y:100},{x:0,y:200}],  onComplete:throwInFinished});
			this.registerForUpdates = true;
		}
		
		private function throwInFinished():void{
			if(owner)
				owner.eventDispatcher.dispatchEvent(new TableWoodGenericEvent(TableWoodGenericEvent.TABLEWOOD_ENTER_EVENT));
			
			PBE.mainStage.dispatchEvent(new TableWoodGenericEvent(TableWoodGenericEvent.TABLEWOOD_ENTER_EVENT));
			this.registerForUpdates = false;
		}
		
		public function throwOutTableWood():void{
			
			spatialComp.canRotate = true;
			spatialComp.canMove = true;
			
			if(owner)
				owner.eventDispatcher.dispatchEvent(new TableWoodGenericEvent(TableWoodGenericEvent.TABLEWOOD_TRHOW_EXIT));
			PBE.mainStage.dispatchEvent(new TableWoodGenericEvent(TableWoodGenericEvent.TABLEWOOD_TRHOW_EXIT));
			
			spatialComp.linearVelocity = new Point(180,-100);
			TweenMax.delayedCall(2,throwOutFinished);	
		}
		
		private function throwOutFinished():void{
			if(owner)
				owner.eventDispatcher.dispatchEvent(new TableWoodGenericEvent(TableWoodGenericEvent.TABLEWOOD_EXIT_EVENT));
			
			this.registerForUpdates = false;
		}
		
		override public function onFrame(e:Number):void{
			spatialComp.position = position;
		}
		
	}
}